#!/usr/bin/env python3
"""
修复导入问题脚本

这个脚本将修复模块中的相对导入问题，使其能够正确导入
"""

import os
import re
from pathlib import Path

def fix_relative_imports(file_path):
    """修复文件中的相对导入"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否有相对导入
        if 'from .' in content:
            print(f"修复文件: {file_path}")
            
            # 替换相对导入为绝对导入
            content = re.sub(r'from \.([a-zA-Z_][a-zA-Z0-9_]*) import', r'from \1 import', content)
            
            # 写回文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            
            print(f"✅ 已修复: {file_path}")
            return True
        else:
            print(f"⏭️  跳过: {file_path} (无相对导入)")
            return False
            
    except Exception as e:
        print(f"❌ 修复失败: {file_path} - {e}")
        return False

def main():
    """主函数"""
    print("🔧 开始修复导入问题...")
    
    # 需要修复的文件列表
    files_to_fix = [
        "hai-optimization/core/result_aggregator.py",
        "hai-optimization/core/webhook_notification_system.py", 
        "hai-optimization/core/latency_monitor.py",
        "hai-optimization/core/degradation_manager.py",
        "hai-optimization/core/fallback_manager.py"
    ]
    
    fixed_count = 0
    
    for file_path in files_to_fix:
        if os.path.exists(file_path):
            if fix_relative_imports(file_path):
                fixed_count += 1
        else:
            print(f"⚠️  文件不存在: {file_path}")
    
    print(f"\n🎉 修复完成! 共修复了 {fixed_count} 个文件")
    
    # 验证修复结果
    print("\n🔍 验证修复结果...")
    for file_path in files_to_fix:
        if os.path.exists(file_path):
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                if 'from .' in content:
                    print(f"❌ 仍有相对导入: {file_path}")
                else:
                    print(f"✅ 导入已修复: {file_path}")
            except Exception as e:
                print(f"⚠️  验证失败: {file_path} - {e}")

if __name__ == "__main__":
    main()
